package com.leinao.team.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.leinao.commons.Response;
import com.leinao.constant.Constant;
import com.leinao.constant.LoginEnum;
import com.leinao.constant.ParameterEnum;
import com.leinao.constant.TeamErrorEnum;
import com.leinao.login.dto.LoginResultDto;
import com.leinao.team.dto.*;
import com.leinao.team.model.PaiTeamInfo;
import com.leinao.team.model.UserInfo;
import com.leinao.team.service.TeamService;
import com.leinao.util.page.PageInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 *
 * @Description 团队控制层
 * @author weiwei
 * @date 2019/4/23 13:22
 * @Version 1.0
 */
@RestController
@CrossOrigin
public class TeamController {

    private static Logger logger = LoggerFactory.getLogger(TeamController.class);
    @Autowired
    private TeamService teamService;

    @ApiOperation(value = "团队近期算力使用情况", notes = "获取团队近期算力使用情况")
    @GetMapping(value = "/team/getTeamCalculationRecentUsage")
    public Response<List<TeamCalculationRecentUsageDto>> getTeamCalculationRecentUsage(HttpServletRequest request,
                                @ApiParam(value = "团队Id", required = true) @RequestParam Long teamId,
                                @ApiParam(value = "查询团队使用算力情况的天数", required = true) @RequestParam Integer daysCount) {
        logger.info("getTeamCalculationRecentUsage param  daysCount: {}", daysCount);

        if (null == teamId) {
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAMID_IS_EMPTY.getSeq(), TeamErrorEnum.TEAMID_IS_EMPTY.getDesc(), null);
        }
        if(daysCount == null){
            daysCount = Constant.CALCULATION_DATE_COUNT;
        }
        // 获取登录用户信息
        String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);

        return teamService.getTeamCalculationRecentUsage(teamId, daysCount, userInfo);
    }
    /**
      * 功能描述: 获取团队列表
      * @param role 传0获取我加入的团队,传1获取我创建的团队,不传返回所有团队
      * @param request
      * @Return:com.leinao.commons.Response<java.util.List<com.leinao.team.dto.TeamListDto>>
      * @Author:HuoPengfei
      * @Date:2019/4/25 14:58
      */
    @ApiOperation(value = "获取团队列表", notes = "获取团队列表")
    @PostMapping(value = "/team/getTeamList")
    @ApiImplicitParam(name = "role", value = "role", required = false, dataType = "int")
    public Response<TeamBeanDto> getTeamList(Integer role, HttpServletRequest request) {
        logger.info("getTeamList param role: {}",role);
        // 获取登录用户信息
        String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
        Response<TeamBeanDto> teamList = teamService.getTeamList(userInfo.getUserId(), role);
        return teamList;
    }
    @ApiOperation(value = "获取团队列表带算力", notes = "获取团队列表带算力")
    @PostMapping(value = "/team/getTeamListWithPower")
    public Response<List<TeamListDto>> getTeamListWithPower(HttpServletRequest request) {
        logger.info("getTeamListWithPower");
        // 获取登录用户信息
        String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
        Response<List<TeamListDto>> teamList = teamService.getTeamListWithPower(userInfo.getUserId());
        return teamList;
    }

    /**
     *
     * @Description:  创建团队接口
     * @param name : 团队名称
     * @param introduction : 团队描述
     * @param emails : 邀请团队成员邮箱，多个以逗号隔开
     * @return: com.leinao.commons.Response<java.lang.Object>
     * @Author: 曹阳
     * @date: 2019/4/23 18:23
     *
     **/
    @ApiOperation(value = "创建团队", notes = "创建团队")
    @PostMapping(value = "/team/creatPaiTeam")
    public Response<PaiTeamInfo> creatPaiTeam(@ApiParam(value = "团队名称", required = true) @RequestParam String name,
                                              @ApiParam(value = "团队简介", required = true) @RequestParam String introduction, @ApiParam(value = "邀请团队成员邮箱", required = true)String emails, HttpServletRequest request) {
        String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
        String userId = userInfo.getUserId();
        if (StringUtils.isBlank(name) || StringUtils.isBlank(introduction)) {
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ParameterEnum.PARAMETER_NULL.getSeq(), ParameterEnum.PARAMETER_NULL.getDesc(),
                    null);
        }
        return teamService.creatPaiTeam(name, introduction, userId, emails);
    }

 /**
   * 功能描述：团队通知
   * @param teamId
   * @param notice
   * @param request
   * @Return:com.leinao.commons.Response<java.lang.Integer>
   * @Author:cuijianxin
   * @Date:2019/4/26 19:20
   */
    @ApiOperation(value = "团队通知", notes = "团队通知")
    @PostMapping(value = "/team/updateNotice")
    public Response<Integer> updateNotice(Long teamId, String notice,HttpServletRequest request){
        logger.info("updateNotice param uuid: {}, notice: {}",teamId,notice);

        if (null==teamId) {
                return Response.error(200, ParameterEnum.PARAMETER_NULL.getSeq(), ParameterEnum.PARAMETER_NULL.getDesc(),
                        null);
        }
        String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);

        Response<Integer> integerResponse = teamService.updateNotice(userInfo.getUserId(),teamId,notice);
        return integerResponse;


    }

    /**
      * 功能描述：用户算例使用状态
      * @param teamId
      * @param userId
      * @param powerStatus
      * @param request
      * @Return:com.leinao.commons.Response<java.lang.Integer>
      * @Author:cuijianxin
      * @Date:2019/4/26 19:20
      */
    @ApiOperation(value = "用户算例使用状态", notes = "用户算例使用状态")
    @PostMapping(value = "/team/updatePowerstatus")
    public Response<Integer> updatePowerstatus(Long teamId,String userId,String powerStatus,HttpServletRequest request) {
       logger.info("updatePowerstatus param teamId: {}, userId: {} powerStatus: {}", teamId,userId,powerStatus);
       if(teamId==null||StringUtils.isBlank(userId)){
           return Response.error(200, ParameterEnum.PARAMETER_NULL.getSeq(), ParameterEnum.PARAMETER_NULL.getDesc(),
                   null);
       }
        String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);

        Response<Integer> integerResponse = teamService.updatePowerstatus(userInfo.getUserId(),teamId,userId,powerStatus);
        return integerResponse;

    }
    /**
     *
     * @Description:  添加团队成员
     * @param userId : 成员ID
     * @param teamId : 团队ID
     * @param data : 邀请链接数据
     * @return: com.leinao.commons.Response<java.lang.Object>
     * @Author: 曹阳
     * @date: 2019/4/24 10:08
     *
     **/
    @ApiOperation(value = "添加团队成员", notes = "添加团队成员")
    @PostMapping(value = "/team/addTeamMemberByUrl")
    public Response<Void> addTeamMemberByUrl(@ApiParam(value = "团队ID", required = true) @RequestParam Long teamId, @ApiParam(value = "成员ID", required = true) @RequestParam String userId, @ApiParam(value = "邀请链接数据", required = true) @RequestParam String data, HttpServletRequest request) {
        if (StringUtils.isBlank(String.valueOf(userId)) || StringUtils.isBlank(String.valueOf(data)) || teamId<1) {
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ParameterEnum.PARAMETER_NULL.getSeq(), ParameterEnum.PARAMETER_NULL.getDesc(),
                    null);
        }
        return teamService.addTeamMember(userId, teamId, data);
    }

    /**
     *
     * @Description: 验证邀请链接
     * @param data : 邀请链接数据
     * @param request :
     * @return: com.leinao.commons.Response<com.leinao.team.dto.TeamMemberInviteDataDto>
     * @Author: 曹阳
     * @date: 2019/4/29 16:08
     *
     **/
    @ApiOperation(value = "验证邀请链接", notes = "验证邀请链接")
    @PostMapping(value = "/team/checkUrlData")
    public Response<TeamMemberInviteDataDto> checkUrlData(@ApiParam(value = "邀请链接数据", required = true) @RequestParam String data, HttpServletRequest request) {
        if (StringUtils.isBlank(String.valueOf(data))) {
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ParameterEnum.PARAMETER_NULL.getSeq(), ParameterEnum.PARAMETER_NULL.getDesc(),
                    null);
        }
        return teamService.checkUrlData(data);
    }


    /**
      * 功能描述: 获取团队详情
      * @param teamId 团队ID
      * @param request
      * @Return:com.leinao.commons.Response<com.leinao.team.model.PaiTeamInfo>
      * @Author:HuoPengfei
      * @Date:2019/4/25 14:58
      */
    @ApiOperation(value = "获取团队详情", notes = "获取团队详情")
    @PostMapping(value = "/team/getTeamDetail")
    public Response<PaiTeamInfo> getTeamDetail(@ApiParam(value = "团队ID", required = true) @RequestParam Long teamId, HttpServletRequest request) {
        logger.info("getTeamDetail param teamId: {}",teamId);
        // 获取登录用户信息
        String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
        if (userInfo == null || StringUtils.isBlank(userInfo.getUserId())) {
            return Response.error(200, LoginEnum.LOGIN_TIMEOUT.getSeq(), LoginEnum.LOGIN_TIMEOUT.getDesc(), null);
        }
        if (null==teamId) {
            return Response.error(200, ParameterEnum.PARAMETER_NULL.getSeq(), ParameterEnum.PARAMETER_NULL.getDesc(),
                    null);
        }
        Response<PaiTeamInfo> teamDetail = teamService.getTeamDetail(teamId, userInfo.getUserId());
        return teamDetail;
    }

    @ApiOperation(value = "查询团队用户的算力使用情况", notes = "查询团队用户的算力使用情况")
    @GetMapping(value = "/team/getTeamUserCalculationRecentUsage")
    public Response<PageInfo> getTeamUserCalculationRecentUsage(HttpServletRequest request,
                                                            @ApiParam(value = "团队Id", required = true) @RequestParam Long teamId,
                                                            @ApiParam(value = "每页展示条数", required = false) @RequestParam Integer pageSize,
                                                            @ApiParam(value = "当前页数", required = false) @RequestParam Integer pageNum) {
        logger.info("getTeamUserCalculationRecentUsage param  teamId: {}", teamId);

        // 获取登录用户信息
        String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
        if (userInfo == null || StringUtils.isBlank(userInfo.getUserId())) {
            return Response.error(200, LoginEnum.LOGIN_TIMEOUT.getSeq(), LoginEnum.LOGIN_TIMEOUT.getDesc(), null);
        }

        if (null == teamId) {
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAMID_IS_EMPTY.getSeq(), TeamErrorEnum.TEAMID_IS_EMPTY.getDesc(), null);
        }
        return teamService.getTeamUserCalculationRecentUsage(teamId, pageSize, pageNum, userInfo);
    }
    /**
     *
     * @Description:  验证用户邮箱接口
     * @param email : 用户邮箱
     * @param teamId : 团队ID
     * @param request :
     * @return: com.leinao.commons.Response<java.lang.Object>
     * @Author: 曹阳
     * @date: 2019/4/24 15:58
     *
     **/
    @ApiOperation(value = "验证用户邮箱接口", notes = "验证用户邮箱接口")
    @PostMapping(value = "/team/getUserInfoByEmail")
    public Response<UserInfo> getUserInfoByEmail(@ApiParam(value = "用户邮箱", required = true) @RequestParam String email, @ApiParam(value = "团队ID", required = true) @RequestParam Long teamId, HttpServletRequest request) {
        if (StringUtils.isBlank(email)) {
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ParameterEnum.PARAMETER_NULL.getSeq(), ParameterEnum.PARAMETER_NULL.getDesc(),
                    null);
        }
        return teamService.getUserInfoByEmail(email, teamId);
    }
    /**
      * 功能描述:
      * @param teamId 团队ID
      * @param currentPage 当前页数
      * @param pageSize 每页条数
      * @param request
      * @Return:com.leinao.commons.Response<com.leinao.util.page.PageInfo>
      * @Author:HuoPengfei
      * @Date:2019/4/25 14:27
      */
    @ApiOperation(value = "获取团队成员详情", notes = "获取团队成员详情")
    @PostMapping(value = "/team/getMemberDetail")
    public Response<PageInfo> getMemberDetail(@ApiParam(value = "团队ID", required = true) @RequestParam Long teamId ,
                                              @ApiParam(value = "当前页数", required = true) @RequestParam int currentPage,
                                              @ApiParam(value = "每页条数", required = true) @RequestParam int pageSize,
                                              HttpServletRequest request) {
        logger.info("getTeamDetail param teamId: {}",teamId);
        // 获取登录用户信息
        String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
        if (null==teamId) {
                return Response.error(200, ParameterEnum.PARAMETER_NULL.getSeq(), ParameterEnum.PARAMETER_NULL.getDesc(),
                null);
            }
            Response<PageInfo> memberDetail = teamService.getMemberDetail(userInfo.getUserId(),teamId, currentPage, pageSize);
            return memberDetail;
    }

     /**
       * 功能描述: 删除成员
       * @param teamId 团队ID
       * @param userId 用户ID
       * @param request
       * @Return:com.leinao.commons.Response<java.lang.Integer>
       * @Author:HuoPengfei
       * @Date:2019/4/25 14:44
       */
    @ApiOperation(value = "删除成员", notes = "删除成员")
    @PostMapping(value = "/team/deleteMember")
    public Response<Integer> deleteMember(@ApiParam(value = "团队ID", required = true) @RequestParam Long teamId ,
                                              @ApiParam(value = "用户ID", required = true) @RequestParam String userId,
                                              HttpServletRequest request) {
        logger.info("deleteMember param teamId: {}", teamId);
        if (null==teamId||StringUtils.isBlank(userId)) {
            return Response.error(200, ParameterEnum.PARAMETER_NULL.getSeq(), ParameterEnum.PARAMETER_NULL.getDesc(),
                    null);
        }
        // 获取登录用户信息
        String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
        Response<Integer> integerResponse = teamService.deleteMember(userInfo.getUserId(), userId, teamId);
        return integerResponse;
    }

    /**
      * 功能描述: 退出团队
      * @param teamId 团队ID
      * @param request
      * @Return:com.leinao.commons.Response<java.lang.Integer>
      * @Author:HuoPengfei
      * @Date:2019/4/25 15:14
      */
    @ApiOperation(value = "退出团队", notes = "退出团队")
    @PostMapping(value = "/team/quitTeam")
    public Response<Integer> quitTeam(@ApiParam(value = "团队ID", required = true) @RequestParam Long teamId ,
                                              HttpServletRequest request) {
        logger.info("quitTeam param teamId: {}", teamId);
        // 获取登录用户信息
        String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
        Response<Integer> integerResponse = teamService.quitTeam(userInfo.getUserId(), teamId);
        return integerResponse;
    }


    @ApiOperation(value = "获取团队使用算力和剩余算力", notes = "获取团队使用算力和剩余算力")
    @PostMapping(value = "/team/getTeamCalculation")
    public Response<TeamCalculationDto> getTeamCalculation(@ApiParam(value = "团队ID", required = true) @RequestParam Long teamId,
                                                           HttpServletRequest request) {
        // 获取登录用户信息
        String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);

        return teamService.getTeamCalculation(teamId, userInfo);
    }

    /**
      * 功能描述: 修改团队简介
      * @param teamId 团队ID
      * @param introduction 团队介绍
      * @param request
      * @Return:com.leinao.commons.Response<java.lang.Integer>
      * @Author:HuoPengfei
      * @Date:2019/4/25 15:44
      */
    @ApiOperation(value = "修改团队简介", notes = "修改团队简介")
    @PostMapping(value = "/team/updateTeamIntro")
    public Response<Integer> updateTeamIntro(@ApiParam(value = "团队ID", required = true) @RequestParam Long teamId ,
                                      @ApiParam(value = "团队介绍", required = true) @RequestParam String introduction ,
                                              HttpServletRequest request) {
        logger.info("quitTeam param teamId: {} introduction: {}", teamId,introduction);
        if(introduction.length()>Constant.TEAM_INTRODUCTION_LENGTH){
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS,TeamErrorEnum.INTRODUCTION_IS_TOO_MANY.getSeq(),TeamErrorEnum.INTRODUCTION_IS_TOO_MANY.getDesc(),null);
        }
        // 获取登录用户信息
        String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);

        Response<Integer> integerResponse = teamService.updateTeamIntro(userInfo.getUserId(),introduction,teamId);
        return integerResponse;
    }

    /**
     *
     * @Description: 发送邮箱邀请连接
     * @param emails : 发送的邮箱，多个以逗号隔开
     * @param teamId : 团队ID
     * @param request :
     * @return: com.leinao.commons.Response<java.util.List<com.leinao.team.dto.EmailResponseDto>>
     * @Author: 曹阳
     * @date: 2019/4/25 16:35
     *
     **/
    @ApiOperation(value = "发送邮箱邀请连接", notes = "发送邮箱邀请连接")
    @PostMapping(value = "/team/sendTeamMemberEmail")
    public Response<Void> sendTeamMemberEmail(@ApiParam(value = "用户邮箱", required = true) @RequestParam String emails, @ApiParam(value = "团队ID", required = true) @RequestParam Long teamId, HttpServletRequest request) {
        if (StringUtils.isBlank(emails)) {
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ParameterEnum.PARAMETER_NULL.getSeq(), ParameterEnum.PARAMETER_NULL.getDesc(),
                    null);
        }
        String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
        String userId = userInfo.getUserId();
        return teamService.sendTeamMemberEmail(emails, teamId, userId);
    }

    /**
     * 功能描述: 解散团队
     * @param teamId 团队ID
     * @param request
     * @Return:com.leinao.commons.Response<java.lang.Integer>
     * @Author:HuoPengfei
     * @Date:2019/4/25 17:47
     */
    @ApiOperation(value = "解散团队", notes = "解散团队")
    @PostMapping(value = "/team/disbandTeam")
    public Response<Integer> disbandTeam(@ApiParam(value = "团队ID", required = true) @RequestParam Long teamId ,
                                         HttpServletRequest request) {
        logger.info("disbandTeam param teamId: {}", teamId);
        // 获取登录用户信息
        String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
        Response<Integer> integerResponse = teamService.disbandTeam(userInfo.getUserId(),teamId);
        return integerResponse;
    }
}


